﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

namespace ET.Score.SharedLibrary.LogCleanner
{
    /// <summary>
    /// 基于日期策略的日志清理器
    /// </summary>
    public class DateLogCleaner : LogCleaner
    {
        private int reserveDays;

        // 支持的日志文件或目录的命名日期格式
        protected static string[] DateFormats =
        {
            "yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd"
        };

        /// <summary>
        /// 清除一段时间(日志保留天数)之前创建的日志
        /// </summary>
        /// <param name="logFolders"></param>
        /// <param name="reserveDays">保留日志天数,大于0</param>
        public DateLogCleaner(IEnumerable<string> logFolders, int reserveDays)
            : base(logFolders)
        {
            if (reserveDays <= 0)
                throw new ArgumentOutOfRangeException("reserveDays must great than 0.");

            this.reserveDays = reserveDays;
        }

        /// <summary>
        /// 确定文件是否满足删除条件，即是日期否在保留天数内
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        protected sealed override bool CanDeleteFile(string filePath)
        {
            DateTime dt = GetDateOfFile(filePath);
            return dt.Date < DateTime.Today.AddDays(-reserveDays);
        }

        /// <summary>
        /// 确定文件夹是否满足删除条件，即是日期否在保留天数内
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        protected sealed override bool CanDeleteFolder(string folderPath)
        {
            DateTime dt = GetDateOfFolder(folderPath);
            return dt.Date < DateTime.Today.AddDays(-reserveDays);
        }

        /// <summary>
        /// 解析(日志)目录的创建日期，根据文件名判断
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        protected virtual DateTime GetDateOfFolder(string folderPath)
        {
            string folderName = Path.GetFileName(folderPath);

            DateTime dt = DateTime.MaxValue;
            if (DateTime.TryParseExact(folderName, DateFormats,
                CultureInfo.InvariantCulture,
                DateTimeStyles.None,
                out dt))
            {
                return dt;
            }
            return DateTime.MaxValue;
        }

        /// <summary>
        /// 解析(日志)文件的创建日期，根据文件名判断
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        protected virtual DateTime GetDateOfFile(string filePath)
        {
            string fileName = Path.GetFileName(filePath);

            DateTime dt = DateTime.MaxValue;
            if (DateTime.TryParseExact(fileName, DateFormats,
                CultureInfo.InvariantCulture,
                DateTimeStyles.None,
                out dt))
            {
                return dt;
            }
            return DateTime.MaxValue;
        }
    }
}